﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Daco.Web.Store;

namespace Daco.Web.Controls
{
    public partial class SearchForm : System.Web.UI.UserControl
    {
        private char[] _separators = new char[] { ',', ';' };

        #region Variables
        public string SearchPage { get; set; }

        public string FormatedSearchPage
        {
            get
            {
                return 
                    string.Format("{0}?cl={1}&ml={2}&ot={3}&ps={4}&pf={5}&pt={6}&h={7}&s={8}",
                        SearchPage, 
                        CategoryFilters != null ? ObjectArrayToString(CategoryFilters)  : string.Empty,
                        ManufactureFilters != null ? ObjectArrayToString(ManufactureFilters) : string.Empty,
                        ViewType,
                        PageSize,
                        PriceFrom,
                        PriceTo,
                        ContainName,
                        SeriesFilters != null ? ObjectArrayToString(SeriesFilters) : string.Empty);
            }
        }

        private object[] _categoryFilters = null;
        public object[] CategoryFilters
        {
            get { return _categoryFilters; }
            protected set { _categoryFilters = value; }
        }

        private object[] _manufactureFilters = null;
        public object[] ManufactureFilters
        {
            get { return _manufactureFilters; }
            protected set { _manufactureFilters = value; }
        }

        private string _containName = null;
        public string ContainName
        {
            get { return _containName; }
            protected set { _containName = value; }
        }

        private object[] _seriesFilters = null;
        public object[] SeriesFilters
        {
            get { return _seriesFilters; }
            protected set { _seriesFilters = value; }
        }
        private float _priceFrom = float.MinValue;
        public float PriceFrom { get { return _priceFrom; } protected set { _priceFrom = value; } }

        private float _priceTo = float.MaxValue;
        public float PriceTo { get { return _priceTo; } set { _priceTo = value; } }

        private EViewType _viewType = EViewType.Detail;
        public EViewType ViewType { get { return _viewType; } protected set { _viewType = value; } }

        public int PageSize { get; protected set; }
        #endregion

        public SearchForm()
        {
            this.PageSize = 16;
            this.Init += new EventHandler(SearchForm_Init);
        }

        void SearchForm_Init(object sender, EventArgs e)
        {
            this.CategoryFilters = ValidObjectArray<int>(Request.QueryString["cl"]);
            this.ManufactureFilters = ValidObjectArray<int>(Request.QueryString["ml"]);

            this.ContainName = string.IsNullOrEmpty(Request.QueryString["h"]) ? string.Empty : Request.QueryString["h"].ToLower();

            this.ContainName = Daco.Utils.CHelper.RemoveIllegalCharacters(this.ContainName);
            if (this.ContainName.Length <= 3) this.ContainName = string.Empty;
            if (this.ContainName.IndexOf("tùy chọn") >= 0) this.ContainName = string.Empty;

            string seriesFilters = string.IsNullOrEmpty(Request.QueryString["s"]) ? string.Empty : Request.QueryString["s"].ToLower();
            if (seriesFilters.Length < 2) seriesFilters = string.Empty;
            if (seriesFilters.IndexOf("tùy chọn") >= 0) seriesFilters = string.Empty;

            this.SeriesFilters = seriesFilters.Split(_separators);
            
            if (string.IsNullOrEmpty(Request.QueryString["pf"]) || !float.TryParse(Request.QueryString["pf"], out _priceFrom))
                _priceFrom = 0;

            if (string.IsNullOrEmpty(Request.QueryString["pt"]) || !float.TryParse(Request.QueryString["pt"], out _priceTo))
                _priceTo = int.MaxValue;

            int pageSize = this.PageSize;
            if (!string.IsNullOrEmpty(Request.QueryString["ps"]) && int.TryParse(Request.QueryString["ps"], out pageSize))
                if (pageSize < 10) pageSize = 10;

            this.PageSize = pageSize;

            try
            {
                this.ViewType = (EViewType)Enum.Parse(typeof(EViewType), Request.QueryString["ot"].Substring(0, Request.QueryString["ot"].Length >= 6 ? 6 : Request.QueryString["ot"].Length), true);
            }
            catch
            {
                this.ViewType = EViewType.Detail;
            }

            SearchPage = Page.ResolveUrl(SearchPage);

            rpProductCategory.DataSource = CProductCategory.GetCategoryTree(-1);
            rpProductCategory.DataBind();

            rpManufacture.DataSource = CProduct.GetManufactures();
            rpManufacture.DataBind();

            Page.ClientScript.RegisterHiddenField("ctrlCategory", ObjectArrayToString(this.CategoryFilters));
            Page.ClientScript.RegisterHiddenField("ctrlManufacture", ObjectArrayToString(this.ManufactureFilters));
            Page.ClientScript.RegisterHiddenField("ctrlViewType", this.ViewType.ToString());
            Page.ClientScript.RegisterHiddenField("ctrlPageSize", this.PageSize.ToString());
            Page.ClientScript.RegisterHiddenField("ctrlProductName", this.ContainName);
            Page.ClientScript.RegisterHiddenField("ctrlPriceFrom", this.PriceFrom.ToString(Config.CSiteConfig.Current.DoubleFormatString));
            Page.ClientScript.RegisterHiddenField("ctrlPriceTo", this.PriceTo.ToString("###"));
            Page.ClientScript.RegisterHiddenField("ctrlSearchPage", this.SearchPage);
        }

        private object[] ValidObjectArray<T>(string input)
        {
            if (string.IsNullOrEmpty(input) || input.IndexOf("Tùy chọn", StringComparison.OrdinalIgnoreCase) >= 0)
                return null;
            else
            {
                List<object> arr = new List<object>();
                string[] idList = input.Split(_separators);

                for (int i = 0; i < idList.Length; i++)
                {
                    try
                    {
                        arr.Add(Convert.ChangeType(idList[i], typeof(T)));
                    }
                    catch
                    {
                    }
                }
                return arr.ToArray();
            }
        }
        private string ObjectArrayToString(object[] arr)
        {
            if (arr != null)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                for (int i = 0; i < arr.Length; i++)
                {
                    if(!string.IsNullOrEmpty(arr[i].ToString()))
                        sb.Append(arr[i]).Append(',');
                }
                if (sb.Length > 1) sb.Remove(sb.Length - 1, 1);

                return sb.ToString();
            }
            else
                return string.Empty;
        }
    }
}